<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/19
 * Time: 17:17
 */
namespace app\business\controller;

use function Sodium\compare;
use think\Controller;
use think\captcha\Captcha;
use think\Db;
use think\Session;

class Login extends Controller
{
	/**
	 * 商家登录首页
	*/
	public function index()
	{
		return view('index');
	}
	
	/**
	 * 验证码
	*/
	public function code()
	{
		$captcha = new Captcha();
		$captcha->fontSize = 30;
		$captcha->length = 4;
		$captcha->expire = 300;
		return $captcha->entry();
	}
	
	/**
	 * 执行登录
	 * @param string post.email 邮箱账号
	 * @param string post.password 邮箱密码
	 * @param string post.code 验证码
	*/
	public function checklogin()
	{
		if(request()->isPost()){
			try{
				$code = input('post.code');
				if(!captcha_check($code)){
					throw new \PDOException('验证码错误');
				}
				$email = input('post.email');
				$password = input('post.password');
				$info = Db::table('business')->where('email',$email)->where('status',2)->find();
				if($info){
					if(encrypt($password) == $info['password']){
						Session::set('business',$info);
						return json(['success'=>'登录成功','type'=>$info['successively']]);
					}else{
						throw new \PDOException('账号或密码错误');
					}
				}else{
					throw new \PDOException('账号不存在');
				}
			}catch (\PDOException $e){
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
		
	}
	
	/**
	 * 退出登录
	*/
	public function outlogin()
	{
		Session::delete('business');
		$this->redirect('business/login/index');
	}
}